package com.galeno.movie;

import com.alibaba.fastjson.JSON;
import com.galeno.json.MovieBean;
import com.galeno.line.Line;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

/**
 * @author galeno
 * @Title:
 * @Description:
 * @date 2021/7/2523:11
 */
public class MovieCount {

    static class MovieMap extends Mapper<LongWritable, Text, IntWritable, DoubleWritable> {

        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            try {
                String line = value.toString();
                MovieBean movieBean = JSON.parseObject(line, MovieBean.class);
                int movie = movieBean.getMovie();
                double rate = movieBean.getRate();
                IntWritable kout = new IntWritable(movie);
                DoubleWritable vout = new DoubleWritable(rate);
                context.write(kout, vout);
            } catch (Exception e) {
                e.printStackTrace();

            }
        }
    }

    static class MovieReducer extends Reducer<IntWritable, DoubleWritable, IntWritable, DoubleWritable> {
        @Override
        protected void reduce(IntWritable key, Iterable<DoubleWritable> values, Context context) throws IOException, InterruptedException {
            double sumrate = 0d;
            for (DoubleWritable value : values) {
                double rate = value.get();
                sumrate = sumrate + rate;
            }
            DoubleWritable vout = new DoubleWritable(sumrate);

            context.write(key, vout);


        }
    }

    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
        Configuration conf = new Configuration();
        conf.set("fs.defaultFS", "file:/");
        Job job = Job.getInstance(conf, "Line");
        job.setMapperClass(MovieMap.class);
        job.setReducerClass(MovieReducer.class);

        job.setMapOutputKeyClass(IntWritable.class);
        job.setOutputValueClass(DoubleWritable.class);
        job.setOutputKeyClass(IntWritable.class);
        job.setMapOutputValueClass(DoubleWritable.class);
        FileInputFormat.setInputPaths(job, new Path("D:/mrdata/movie/input"));
        FileOutputFormat.setOutputPath(job, new Path("D:/mrdata/movie/omg"));

        job.waitForCompletion(true);
    }
}
